package com.mrd.util.html2pdf;


import com.mrd.framework.utils.SpringUtils;
import com.mrd.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 网页转图片处理类，使用外部CMD
 * Created by dengdc on 2017/7/16.
 */
public class PhantomjsTools {
    private static final Logger _logger = LoggerFactory.getLogger(PhantomjsTools.class);

    private static String _shellCommand = "";

    private static String baseDir = "";


    static {
        String osName = System.getProperty("os.name");
        if(osName.contains("Windows")){
            _shellCommand = PhantomjsTools.class.getResource("/phantomjs/windows").getPath().replaceAll("^/", "")
                    + File.separator + "phantomjs "
                    + PhantomjsTools.class.getResource("/phantomjs/windows/rasterize.js").getPath().replaceAll("^/", "");
        }else{
            _shellCommand = "phantomjs " + PhantomjsTools.class.getResource("/phantomjs/windows/rasterize.js").getPath();
        }
        baseDir = SpringUtils.getConfigProperties("file.declaration.pdf.dir");
    }

    private static PhantomjsTools phantomjsTools = null;

    private String file;
    private String fileName;
    private String size;

    public enum FileType {
        PNG,JPG,PDF;

        @Override
        public String toString() {
            String str = null;
            switch (this){
                case PNG:
                    str = ".png";
                    break;
                case JPG:
                    str = ".jpg";
                    break;
                case PDF:
                    str = ".pdf";
                default:
            }
            return str;
        }
    }

    /**
     * 构造截图类
     * @param saveFileToDir 转换完成时候要存储的文件夹
     * @param type 要将html转成什么类型的文件
     */
    public PhantomjsTools(String saveFileToDir, FileType type) {
        this.fileName =  UUID.randomUUID().toString() + type.toString();
        file = saveFileToDir + File.separator + this.fileName;
    }

    /**
     * 执行将url指向的Html页面转成 图片或pdf
     * @param url 目标网页地址
     */
    public void exec(String url) throws IOException {
        String cmdString = _shellCommand + " " + url + " " + this.file + " " + (this.size != null ? this.size : "");
        System.out.println(cmdString);
        exeCmd(cmdString);
    }

    /**
     * 执行对http地址转换成pdf文件
     * @param url 要转换的http地址
     * @param saveToDir 保存文件的路径
     */
    public static synchronized String execUrlToPdf(String url, String fileName, String saveToDir){
        if(phantomjsTools == null){
            phantomjsTools = new PhantomjsTools(saveToDir, FileType.PDF);
        }else {
            phantomjsTools.setFile(getSaveDirPath(saveToDir), fileName, FileType.PDF);
        }
        long begin = System.currentTimeMillis();
        String infoPrefix = "将" + url + "转成pdf";
        _logger.info("开始: " + infoPrefix);
        try {
            phantomjsTools.setSize("1024*768px");
            phantomjsTools.exec(url);
        } catch (IOException e) {
            _logger.error(infoPrefix + "时发生异常："+e.getMessage());
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        _logger.info("完成: " + infoPrefix);
        _logger.info(infoPrefix + "耗时（ms）: " + (end - begin));
        return phantomjsTools.getFileName();
    }

    /**
     * 格式如： 1080px 或 1080px*768px
     * 假如指定了高度，最后生成的文件可能会留白或者被裁剪
     * @param size 尺寸
     */
    public void setSize(String size){
        this.size = size;
    }

    private void setFile(String dir, String fileName, FileType fileType) {
        if(StringUtils.isNotEmpty(fileName)){
            this.fileName = fileName;
        }else {
            this.fileName =  UUID.randomUUID().toString() + fileType.toString();
        }
        file = dir + File.separator + this.fileName;
    }
    private String getFileName(){
        return this.fileName;
    }

    /**
     * 执行CMD命令
     */
    private static void exeCmd(String commandStr) {
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            if (p.waitFor() != 0 && p.exitValue() == 1) {
                throw new Exception(commandStr + " 没能正常保存为pdf");
            }
        } catch (Exception e) {
            _logger.error(e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        //file:///C:/Users/Administrator/Desktop/pdf_pt/order.html
//        new PhantomTools(1).getByteImg("http://www.baidu.com");
        System.out.println(System.getProperty("os.name"));
//        execUrlToPdf("file:///C:/Users/dengdc/Desktop/pdf_pt/order-read.html", "C:\\Users\\dengdc\\Desktop\\pdf_pt");
    }

    private static String getSaveDirPath(String dateStr){
//        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
//        String dateStr = yyyyMMdd.format(new Date());
        String year = dateStr.substring(0, 4);
        String month = dateStr.substring(4, 6);
        String day = dateStr.substring(6);
        File saveDir = new File(baseDir + File.separator + year + File.separator + month + File.separator + day);
        if(!saveDir.exists()){
            saveDir.mkdirs();
        }
        return saveDir.getAbsolutePath();
    }
}
